﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using StockFinder.Model;

namespace StockFinder.Services.ChartPatterns
{
    /* find the highest and lowest point in the last 8 weeks
     * and pattern fits if it has moved 100% or more */

    /// <summary>
    /// Stock has moved 100% -> 120% in 4 to 8 weeks
    /// Small decline of 20% to 25% pullback.
    /// </summary>
    public class HighTightFlagPattern : IChartPattern
    {
        private const int BASE_LENGTH = 11;
        private const int MINIMUM_PRICE_MOVEMENT = 100;

        #region IChartPattern Members

        public ChartPatternResult Apply(Symbol symbol)
        {
            ChartPatternResult result = new ChartPatternResult();
            result.DoesFit = false;

            //make sure we have prices
            if (symbol.WeeklyPrices != null && symbol.WeeklyPrices.Count >= BASE_LENGTH)
            {
                WeeklyPrice weeklyPrice = null;

                //get weekly high and low
                decimal highestPrice = symbol.WeeklyPrices[0].GetWeeklyHigh();
                decimal lowestPrice = symbol.WeeklyPrices[0].GetWeeklyLow();

                int highWeek = 0;
                int lowWeek = 0;

                //loop the weekly prices
                for (int i = 1; i < BASE_LENGTH; i++)
                {
                    //reference this weekly price
                    weeklyPrice = symbol.WeeklyPrices[i];

                    //new high mark
                    if (weeklyPrice.GetWeeklyHigh() > highestPrice)
                    {
                        highestPrice = weeklyPrice.GetWeeklyHigh();

                        highWeek = i;
                    }

                    //new low mark
                    if (weeklyPrice.GetWeeklyLow() < lowestPrice)
                    {
                        lowestPrice = weeklyPrice.GetWeeklyLow();

                        lowWeek = i;
                    }
                }

                //check the price movement
                decimal priceMovement = (highestPrice - lowestPrice);

                priceMovement = priceMovement / lowestPrice;

                priceMovement = priceMovement * 100;

                //did the smbol move enough
                if (priceMovement >= MINIMUM_PRICE_MOVEMENT)
                {
                    //yes check whether the high week occurred more recently than low week                    
                    result.DoesFit = true;                   
                }
            }

            return result;
        }

        #endregion
    }
}
